package com.pearadmin.pro.modules.applet.rest;


import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.pearadmin.pro.common.secure.uutoken.SecureUserToken;
import com.pearadmin.pro.common.secure.uutoken.SecureUserTokenService;
import com.pearadmin.pro.common.web.base.BaseController;
import com.pearadmin.pro.modules.applet.config.SHA1;
import com.pearadmin.pro.modules.applet.config.WeiXinConfig;
import com.pearadmin.pro.modules.applet.config.WxjskUtil;
import com.pearadmin.pro.modules.applet.vo.AppletLoginParam;
import com.pearadmin.pro.modules.stu.domain.StuBusp;
import com.pearadmin.pro.modules.stu.service.StuBuspService;
import com.pearadmin.pro.modules.sys.domain.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.pearadmin.pro.common.web.domain.Result;

import java.util.*;

/**
 * @author bysujc
 * @version 1.0.0
 * @ClassName ClientController.java
 * @Description 小程序登录
 * @createTime 2021年09月19日 11:38:00
 */
@Api(tags = "小程序用户登录")
@RestController
@RequestMapping("/client")
public class ClientController extends BaseController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WeiXinConfig weiXinConfig;
    @Autowired
    private StuBuspService stuBuspService;
    @Autowired
    private SecureUserTokenService secureUserTokenService;//token


    @ApiOperation(value = "微信小程序自动登陆", notes = "微信小程序自动登陆", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "code", required = true, dataType = "String"),
            @ApiImplicitParam(name = "state", value = "state 微信自定义返回字段 非必填", required = false, dataType = "String"),})
    @RequestMapping("/wxMinLogin")
    public Result appletLogin(@RequestBody AppletLoginParam req) {
        log.info(JSONObject.toJSONString(req));
        JSONObject phoneJson = new JSONObject();
        String code = req.getCode();
        if (StringUtils.isEmpty(code)) {
            return failure("code值为空");
        }
        String userInfos = req.getUserInfo();
        String signature = req.getSignature();
        Map<String, Object> resultObj = new HashMap<String, Object>();
        log.info("1111={},222={},333={}", weiXinConfig.getWebAccessTokenhttps(), weiXinConfig.getWeixinMpMiniAppid(),
                weiXinConfig.getWeixinMpMiniAppsecret());
        String requestUrl = String.format(weiXinConfig.getWebAccessTokenhttps(), weiXinConfig.getWeixinMpMiniAppid(),
                weiXinConfig.getWeixinMpMiniAppsecret(), code);
        JSONObject sessionData = null;
        try {
            log.info(requestUrl);
            String message = HttpUtil.get(requestUrl);
            sessionData = JSONObject.parseObject(message);
            log.info(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == sessionData || StringUtils.isEmpty(sessionData.getString("openid"))) {
            return failure("微信解析失败");
        }
        //验证用户信息完整性
        String sha1 = SHA1.getSha1(userInfos + sessionData.getString("session_key"));
        //解密手机号
        String sessKey = sessionData.getString("session_key");
        //微信unionid
        String unionid = sessionData.getString("unionid");
        //微信openid
        String openid = sessionData.getString("openid");

        JSONObject unindJson = new JSONObject();
        StuBusp stuBusp = null;
        if (StringUtils.isNotEmpty(unionid)) {
            stuBusp = stuBuspService.selectStuBuspByWeixinunid(unionid);
        } else if (StringUtils.isNotEmpty(req.getU_iv()) && StringUtils.isNotEmpty(req.getU_encrypted_data())) {
            String unindJsonStr = WxjskUtil.decrypt(sessKey, req.getU_iv(), req.getU_encrypted_data());
            log.info("unindJsonStr={}", unindJsonStr);
            if (StringUtils.isNotEmpty(unindJsonStr)) {
                unindJson = JSONObject.parseObject(unindJsonStr);
                Object unionIdObj = unindJson.get("unionId");
                if (null != unionIdObj) {
                    unionid = unionIdObj.toString();
                    stuBusp = stuBuspService.selectStuBuspByWeixinunid(unionid);
                }
            }
        }
        Optional<StuBusp> buspOptional = Optional.ofNullable(stuBusp);
        if (!buspOptional.isPresent()) {
            String phoneJsonStr = WxjskUtil.decrypt(sessKey, req.getIv(), req.getEncrypted_data());
            if (StringUtils.isEmpty(phoneJsonStr)) {
                return failure("微信解析失败");
            }
            log.info("phoneNnmJson={}", phoneJsonStr);
            phoneJson = JSONObject.parseObject(phoneJsonStr);
            String phoneNum = null;
            openid = phoneJson.get("openId").toString();
            unionid = phoneJson.get("unionId").toString();
            if (null != phoneJson.get("purePhoneNumber")) {
                phoneNum = String.valueOf(phoneJson.get("purePhoneNumber")).trim();
                if (StringUtils.isNotEmpty(phoneNum)) {
                    stuBusp = stuBuspService.selectStuBuspByPhone(phoneNum);
                }
            }
            if (null == stuBusp) {
                stuBusp = new StuBusp();
                if (StringUtils.isNotEmpty(phoneNum)) {
                    stuBusp.setLocalPhone(phoneNum); // 用户国内联系方式
                }
                if (Optional.ofNullable(phoneJson.get("avatarUrl")).isPresent()) {
                    stuBusp.setHeadUrl(phoneJson.get("avatarUrl").toString()); //头像
                }
                stuBusp.setUnionid(unionid);
                stuBusp.setOpenid(openid);
                stuBuspService.saveOrUpdate(stuBusp);
            }
        }

        /**
         * 设置账户token
         *
         */

//        SecureUser secureUser = new SecureUser();
//        //用的是学生的ID生成token
//        secureUser.setUsername("1437705562545983490");
//        secureUser.setId("1437705562545983490");

        SysUser secureUser = new SysUser();
        secureUser.setId(Convert.toStr(stuBusp.getId()));
        secureUser.setUsername(Convert.toStr(stuBusp.getId()));
        secureUser.setPassword(Convert.toStr(stuBusp.getId()));
        secureUser.setEnable(true);
        secureUser.setLocked(false);
        secureUser.setRoles(new ArrayList<>());
        SecureUserToken token = secureUserTokenService.createToken(secureUser);
        log.info("----------------小程序登录token:-------------" + token);
        log.info(token.getToken());
        String tokenKey = secureUserTokenService.saveToken(token);
        log.info("----------------小程序登录token-key:------------" + tokenKey);

        Map<String, Object> map = new HashMap<>();
        map.put("code", "200");
        map.put("data", stuBusp.getId());
        map.put("msg", "登录成功");
        map.put("success", true);
        map.put("timeStamp", System.currentTimeMillis());
        map.put("token", token.getToken());
        map.put("tokenKey", tokenKey);
        return success(map);
    }


}
